package com.ssmeasy.jdgl.serviceImpl;

import com.ssmeasy.jdgl.dao.UserMapper;
import com.ssmeasy.jdgl.pojo.User;
import com.ssmeasy.jdgl.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    /**
     * 登陆
     * @param username
     * @param password
     * @return  验证失败返回null
     */
    @Override
    public User login(String username, String password) {
        if(username==null || password==null)
            return null;

        //对密码进行加密
        Md5Hash md5Hash = new Md5Hash(password,username,100);

        //查找对应用户
        User user = userMapper.selectByUsername(username);
        String a = md5Hash.toString();
        //System.out.println(a);
        if(user!=null && user.getPassword().equals(md5Hash.toString())){
            return user;
        }

        return null;

    }

    /**
     * 通过用户名获取用户
     *
     * @param username
     * @return 失败返回null
     */
    @Override
    public User getByUsername(String username) {
        if(username==null)
            return null;

        return userMapper.selectByUsername(username);
    }


    @Override
    @Transactional
    public void updatePassword(String username, String oldPassword, String newPassword) throws Exception {
        //通过用户名查找用户密码
        User user = userMapper.selectByUsername(username);

        if(user == null)
            throw new Exception("用户不存在");

        //验证旧密码是否正确
        Md5Hash md5Hash = new Md5Hash(oldPassword,username,100);
        if(!user.getPassword().equals(md5Hash.toString())){
            throw  new Exception("密码错误");
        }
        //创建新密码
        md5Hash = new Md5Hash(newPassword,username,100);
        user.setPassword(md5Hash.toString());

        //更新密码
        userMapper.updateByPrimaryKey(user);

    }

}
